import time
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
from A3mall_pytest.pytest_a3mall_db import Mydb
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from A3mall_pytest.common import reed_csv
from A3mall_pytest.Tools import Tools
import logging
from loguru import logger

logger.add('pytest_yw1.log', level='DEBUG')

tt = reed_csv()

# 测试固件：浏览器初始化
# 当你使用这个夹具时，pytest 会自动为每个参数值生成一个新的测试函数，每个测试函数都会接收到相应的参数值(每个用例执行三次：三个浏览器个执行一次)
# @pytest.fixture(scope="function", params=["chromium", "firefox", "webkit"])
@pytest.fixture(scope="function", params=tt.read_data_from_csv('E:\zhuangaoer_pyCharm\zhuangaowuday1\A3mall_pytest\edit_mm.csv'))
def get_driver(request):
    driver = webdriver.Firefox()
    driver.maximize_window()
    driver.get('http://10.59.9.14:7003/')
    # 连接数据库
    db = Mydb('10.59.9.14', 'root', 'yidong666', 'a3mall', '3306')
    params = request.param
    yield driver, db, params
    # 关闭数据库连接
    db.close()
    time.sleep(10)
    driver.quit()

class Test_a3mall_yw4():

    def setup(self):
        Tools().log4()
        print('start case 01')
        logging.info('start case 01')
        logger.info('start case 01')

    def teardown(self):
        print('case 01 end')
        logging.info('case 01 end')
        logger.info('case 01 end')

    userprice = None

    def test_a3mall_01(self, get_driver):
        try:
            self.driver, self.db, param = get_driver  # 接收 fixture 传递的参数
            jmm, xmm, qrmm, casename, expected = param  # 解包 Excel 数据
            # 1、点击登录
            self.driver.find_element(By.XPATH, '//a[@href="/home/login.html"]').click()
            # 断言1：会员登录
            dy1 = self.driver.find_element(By.CLASS_NAME, 'reg-new').text
            print(f'dy1:{dy1}')
            assert '会员登录' == dy1, "字符串不相等"
            # 2、输入用户名
            self.driver.find_element(By.NAME, 'username').send_keys('15985645484')
            # 3、输入密码
            self.driver.find_element(By.NAME, 'password').send_keys('123456')
            # 4、勾选记住密码
            self.driver.find_element(By.CSS_SELECTOR, '#theForm > div.agree-clause > span > label > input').click()
            # 强制等待10秒，输入验证码
            time.sleep(10)
            # 5、点击登录按钮
            self.driver.find_element(By.CLASS_NAME, 'finish-btn').click()
            time.sleep(5)
            # 断言2：欢迎回来，小高4
            dy2 = self.driver.find_element(By.XPATH, '/html/body/div[5]/div[2]/div[1]/div[2]/div[2]/ul/li[1]').text
            print(f'dy2:{dy2}')
            assert '欢迎回来' in dy2, "欢迎回来不在dy2中"
            price = self.driver.find_element(By.XPATH,
                                             '/html/body/div[5]/div[2]/div[1]/div[2]/div[2]/ul/li[4]/span').text
            price1 = str(price).split('¥ ')
            print(f"用户总金额:{price1[1]}")
            Test_a3mall_yw4.userprice = float(price1[1])

            # 业务逻辑 **************************
            print(f'*****业务：{casename}')
            time.sleep(1)
            # 点击修改密码
            self.driver.find_element(By.XPATH, '/html/body/div[5]/div[1]/div[2]/div[4]/div[2]/ul/li[3]/a').click()
            time.sleep(1)
            # 浏览器返回事件
            self.driver.back()
            time.sleep(2)
            # 浏览器前进事件
            self.driver.forward()
            time.sleep(2)
            # 浏览器刷新事件
            self.driver.refresh()
            time.sleep(2)
            # 隐式等待
            self.driver.implicitly_wait(10)
            # 断言：修改密码
            pw = self.driver.find_element(By.CLASS_NAME, 'morder-title').text
            assert '修改密码' == pw
            # 输入旧密码
            jpassword = WebDriverWait(self.driver, 20, 0.5).until(
                EC.presence_of_element_located(
                    (By.CSS_SELECTOR, '#theForm > table > tbody > tr:nth-child(1) > td > span > input'))
            )
            jpassword.send_keys(jmm)
            # 输入新密码：#theForm > table > tbody > tr:nth-child(2) > td > span > input
            xpassword = WebDriverWait(self.driver, 20, 0.5).until(
                EC.presence_of_element_located(
                    (By.CSS_SELECTOR, '#theForm > table > tbody > tr:nth-child(2) > td > span > input'))
            )
            xpassword.send_keys(xmm)
            # 输入确认新密码:
            qrpassword = WebDriverWait(self.driver, 20, 0.5).until(
                EC.presence_of_element_located(
                    (By.CSS_SELECTOR, '#theForm > table > tbody > tr:nth-child(3) > td > span > input'))
            )
            qrpassword.send_keys(qrmm)

            # 点击提交
            self.driver.find_element(By.XPATH,
                                     '/html/body/div[5]/div[2]/div/div[2]/form/table/tbody/tr[4]/td/p/a').click()
            # 断言:
            if '修改成功' in casename:
                assert '修改成功' in expected
            else:
                assert '修改失败' in expected
        except Exception as e:
            # time.strftime：这是Python的time模块中的一个函数，用于将时间格式化为指定的字符串格式
            # time.localtime()：获取当前本地时间
            t = time.strftime('%Y%m%d%H%M%S', time.localtime())
            # save_screenshot：这是Webdriver的一个方法，用于保存当前浏览器窗口的截图
            self.driver.save_screenshot('E:\zhuangaoer_pyCharm\zhuangaowuday1\A3mall_pytest/'+t + 'pytest_yw4.png')
            print(f'异常信息：{e}')
            raise








if __name__ == '__main__':
    pytest.main(['pytest_yw1_test.py'])
# pytest --html=./A3mall_pytest/pytest_yw4_01.html ./A3mall_pytest/pytest_yw4_test.py



